package com.waa.gulimall.product.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.waa.gulimall.product.entity.CategoryBrandRelationEntity;
import com.waa.gulimall.product.service.CategoryBrandRelationService;
import com.waa.gulimall.product.vo.Catelog2Vo;
import org.apache.commons.lang.StringUtils;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.waa.gulimall.common.utils.PageUtils;
import com.waa.gulimall.common.utils.Query;

import com.waa.gulimall.product.dao.CategoryDao;
import com.waa.gulimall.product.entity.CategoryEntity;
import com.waa.gulimall.product.service.CategoryService;
import org.springframework.transaction.annotation.Transactional;


@Service("categoryService")
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, CategoryEntity> implements CategoryService {
    @Autowired
    private CategoryBrandRelationService categoryBrandRelationService;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private RedissonClient redissonClient;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<CategoryEntity> page = this.page(
                new Query<CategoryEntity>().getPage(params),
                new QueryWrapper<CategoryEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public List<CategoryEntity> listWithTree() {
        //1.查出所有分类
        List<CategoryEntity> categoryEntities = baseMapper.selectList(null);

        //2.组装成父子的树形结构
        //2.1找出所有的一级分类
        List<CategoryEntity> level1Menu = categoryEntities.stream().filter(categoryEntity -> {
            return categoryEntity.getParentCid() == 0;
        }).map((menu) -> {
            menu.setChildren(getChildrens(menu, categoryEntities));
            return menu;
        }).sorted((menu1, menu2) -> {
            return (menu1.getSort() == null ? 0 : menu1.getSort()) - (menu2.getSort() == null ? 0 : menu2.getSort());
        }).collect(Collectors.toList());
        return level1Menu;
    }

    @Override
    public void removeMenuByids(List<Long> asList) {
        //TODO 检查当前删除的菜单，是否被别的地方引用
        baseMapper.deleteBatchIds(asList);
    }

    //查找全路径
    @Override
    public Long[] findCatelogPath(Long catelogId) {
        final ArrayList<Long> paths = new ArrayList<>();
        findParentPath(catelogId, paths);
        Collections.reverse(paths);
        return (Long[]) paths.toArray(new Long[paths.size()]);
    }
  /*
  * 级联更新所有关联的数据
  * */
    @Override
    @CacheEvict(value = "categorys",allEntries = true)
    @Transactional
    public void updateDetail(CategoryEntity category) {
        //保证冗余字段的一致
        this.updateById(category);
        if (!StringUtils.isEmpty(category.getName())) {
            //同步更新其他关联表中的数据
            final CategoryBrandRelationEntity categoryBrandRelationEntity = new CategoryBrandRelationEntity();
            categoryBrandRelationEntity.setBrandName(category.getName());
            categoryBrandRelationEntity.setBrandId(category.getCatId());
            categoryBrandRelationService.update(categoryBrandRelationEntity, new UpdateWrapper<CategoryBrandRelationEntity>().eq("catelog_id", category.getCatId()));
        }
    }

    @Override
    @Cacheable(value = "categorys",key = "'catagoryLeve1JsonData'")
    public List<CategoryEntity> getLeve1Categorys() {
        final List<CategoryEntity> categoryEntities = baseMapper.selectList(new QueryWrapper<CategoryEntity>().eq("cat_level", 1));
        return categoryEntities;
    }

    @Override
    @Cacheable(value = "categorys",key = "'catagoryJsonData'")
    public Map<String, List<Catelog2Vo>> getCatalogJson() {
        final Map<String, List<Catelog2Vo>> catalogFromDB2 = getCatalogFromDB2();
        return catalogFromDB2;
    }
    //@Override
    public Map<String, List<Catelog2Vo>> getCatalogJson2() {
        //给缓存中放入json，拿出json字符窜
        //1.假如缓存逻辑，缓存中存的·数据是json字符串
        //json跨语言，跨平台兼容
        final String catalogJSON = stringRedisTemplate.opsForValue().get("catalogJSON");
        if (StringUtils.isEmpty(catalogJSON)) {
            //缓存中没有，查询数据库
            final Map<String, List<Catelog2Vo>> catalogJsonForDB = getCatalogJsonForDBWithRedissonLock();
//            //查到数据转换为json放入到缓存中国
//            final String jsonString = JSON.toJSONString(catalogJsonForDB);
//            stringRedisTemplate.opsForValue().set("catalogJSON",jsonString);
            return catalogJsonForDB;
        }
        //转为我们指定的对象
        final Map<String, List<Catelog2Vo>> result = JSON.parseObject(catalogJSON, new TypeReference<Map<String, List<Catelog2Vo>>>() {
        });
        return result;
    }

    public Map<String, List<Catelog2Vo>> getCatalogJsonForDBWithRedissonLock() {
        //占分布式锁，去redis流,保证加锁原子性
        //锁的粒度要设置精细，具体到缓存的是某个数据
        final RLock rLock = redissonClient.getLock("catagory-lock");
        rLock.lock();
        System.out.println("获取分布式锁成功");
        //加锁成功。。。。执行业务
        final Map<String, List<Catelog2Vo>> catalogFromDB;
        try {
            catalogFromDB = getCatalogFromDB();
        } finally {
            rLock.unlock();
        }
        //stringRedisTemplate.delete("lock");//删除锁
        return catalogFromDB;

    }

    public Map<String, List<Catelog2Vo>> getCatalogJsonForDBWithRedis() {
        //占分布式锁，去redis流,保证加锁原子性
        final String token = UUID.randomUUID().toString();
        final Boolean lock1 = stringRedisTemplate.opsForValue().setIfAbsent("lock", token, 300, TimeUnit.SECONDS);
        if (lock1) {
            System.out.println("获取分布式锁成功");
            //加锁成功。。。。执行业务
            final Map<String, List<Catelog2Vo>> catalogFromDB;
            try {
                catalogFromDB = getCatalogFromDB();
            } finally {
                //删除锁也要保证原子性
                String script = "if redis.call('get',KEYS[1]) == ARGV[1] then return redis.call('del',KEYS[1]) else return 0 end";
                final Long lock2 = stringRedisTemplate.execute(new DefaultRedisScript<Long>(script, Long.class), Arrays.asList("lock"), token);
            }
            //stringRedisTemplate.delete("lock");//删除锁
            return catalogFromDB;
        } else {
            //加锁失败重新synchronized
            return getCatalogJsonForDBWithRedis();
        }
    }

    //TODO 本地锁
    public Map<String, List<Catelog2Vo>> getCatalogJsonForDBWithLocal() {
        synchronized (this) {
            final String catalogJSON = stringRedisTemplate.opsForValue().get("catalogJSON");
            if (StringUtils.isEmpty(catalogJSON)) {
                final Map<String, List<Catelog2Vo>> catalogFromDB = getCatalogFromDB();
                return catalogFromDB;
            }
            //如果缓存中有我们使用缓存中的
            final Map<String, List<Catelog2Vo>> result = JSON.parseObject(catalogJSON, new TypeReference<Map<String, List<Catelog2Vo>>>() {
            });
            return result;
        }

    }

    public Map<String, List<Catelog2Vo>> getCatalogFromDB() {
        System.out.println("查了数据库。。。");
        //将数据库多次查询变为一次
        final List<CategoryEntity> selectList = baseMapper.selectList(null);
        //查出所有的一级分类
        final List<CategoryEntity> leve1Categorys = getLeve1Categorys();
        //封装数据
        final Map<String, List<Catelog2Vo>> map = leve1Categorys.stream().collect(Collectors.toMap(k -> k.getCatId().toString(), v -> {
            final List<CategoryEntity> categoryEntities = getParentCid(selectList, v.getCatId());
            //封装上免得结果
            List<Catelog2Vo> catelog2Vos = null;
            if (categoryEntities != null) {
                catelog2Vos = categoryEntities.stream().map(l2 -> {
                    final Catelog2Vo catelog2Vo = new Catelog2Vo(v.getCatId().toString(), null, l2.getCatId().toString(), l2.getName());
                    //找到当前二级分类的三级分类封成vo
                    final List<CategoryEntity> level3Catelog = getParentCid(selectList, l2.getCatId());
                    if (level3Catelog != null) {
                        final List<Catelog2Vo.Catelog3Vo> collect = level3Catelog.stream().map(l3 -> {
                            final Catelog2Vo.Catelog3Vo catelog3Vo1 = new Catelog2Vo.Catelog3Vo(l2.getCatId().toString(), l3.getCatId().toString(), l3.getName());
                            return catelog3Vo1;
                        }).collect(Collectors.toList());
                        catelog2Vo.setCatalog3List(collect);
                    }
                    return catelog2Vo;
                }).collect(Collectors.toList());
            }
            return catelog2Vos;
        }));
        //查到数据转换为json放入到缓存中,为了解决缓存击穿问题要将放入缓存这个各操作也放在锁里面
        final String jsonString = JSON.toJSONString(map);
        stringRedisTemplate.opsForValue().set("catalogJSON", jsonString);
        return map;
    }
    public Map<String, List<Catelog2Vo>> getCatalogFromDB2() {
        System.out.println("查了数据库。。。");
        //将数据库多次查询变为一次
        final List<CategoryEntity> selectList = baseMapper.selectList(null);
        //查出所有的一级分类
        final List<CategoryEntity> leve1Categorys = getLeve1Categorys();
        //封装数据
        final Map<String, List<Catelog2Vo>> map = leve1Categorys.stream().collect(Collectors.toMap(k -> k.getCatId().toString(), v -> {
            final List<CategoryEntity> categoryEntities = getParentCid(selectList, v.getCatId());
            //封装上免得结果
            List<Catelog2Vo> catelog2Vos = null;
            if (categoryEntities != null) {
                catelog2Vos = categoryEntities.stream().map(l2 -> {
                    final Catelog2Vo catelog2Vo = new Catelog2Vo(v.getCatId().toString(), null, l2.getCatId().toString(), l2.getName());
                    //找到当前二级分类的三级分类封成vo
                    final List<CategoryEntity> level3Catelog = getParentCid(selectList, l2.getCatId());
                    if (level3Catelog != null) {
                        final List<Catelog2Vo.Catelog3Vo> collect = level3Catelog.stream().map(l3 -> {
                            final Catelog2Vo.Catelog3Vo catelog3Vo1 = new Catelog2Vo.Catelog3Vo(l2.getCatId().toString(), l3.getCatId().toString(), l3.getName());
                            return catelog3Vo1;
                        }).collect(Collectors.toList());
                        catelog2Vo.setCatalog3List(collect);
                    }
                    return catelog2Vo;
                }).collect(Collectors.toList());
            }
            return catelog2Vos;
        }));
        return map;
    }

    public List<CategoryEntity> getParentCid(List<CategoryEntity> selectList, Long parent_id) {
        final List<CategoryEntity> collect = selectList.stream().filter(item -> item.getParentCid() == parent_id).collect(Collectors.toList());
        return collect;
    }

    private List<Long> findParentPath(Long catelogId, ArrayList<Long> paths) {
        //收集当前节点id
        paths.add(catelogId);
        final CategoryEntity uplevel = this.getById(catelogId);
        if (uplevel.getParentCid() != 0) {
            findParentPath(uplevel.getParentCid(), paths);
        }
        return paths;
    }

    //递归查找所有菜单的子菜单
    private List<CategoryEntity> getChildrens(CategoryEntity root, List<CategoryEntity> all) {
        List<CategoryEntity> chlidren = all.stream().filter(categoryEntity -> {
            return categoryEntity.getParentCid() == root.getCatId();
        }).map((menu) -> {
            //找到子菜单
            menu.setChildren(getChildrens(menu, all));
            return menu;
            //菜单的排序
        }).sorted((menu1, menu2) -> {
            return (menu1.getSort() == null ? 0 : menu1.getSort()) - (menu2.getSort() == null ? 0 : menu2.getSort());
        }).collect(Collectors.toList());
        return chlidren;
    }

}